package org.boxsql.persistenceEngine;

import java.lang.reflect.Field;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import org.boxsql.templateEngine.TemplateEngine;

public class SQLEngine {

	private Fields configuraCampo;
	private Entity tabelas;
    private Map<String, String> keys = new HashMap<String, String>();

	public String getSelect(final Class className) {
		int linhaAtual = 0;
		StringBuilder sb = new StringBuilder();
		sb.append("select ");
		for (Field field : className.getDeclaredFields()) {
			int totalCampos = className.getDeclaredFields().length;
			linhaAtual += 1;
			for (Annotation anno : field.getAnnotations()) {
				if (anno instanceof Fields) {
					configuraCampo = (Fields) anno;
					String virgula = (linhaAtual < totalCampos) ? "," : " ";
					sb.append("  " + configuraCampo.fieldName() + " as "
							+ field.getName() + virgula);
				}
			}

		}
		for (Annotation annoClass : className.getAnnotations()) {
			tabelas = (Entity) annoClass;
			if (annoClass instanceof Entity) {
				sb.append("  from " + tabelas.tableName());
			}

		}
		System.out.println("Teste: " + sb.toString());
		return sb.toString();

	}

	public String getUpdate(final Object obj) {
		int linhaAtual = 0;
		int linhaAtualWhere = 0;

		StringBuilder sb = new StringBuilder();
		StringBuilder sbWhere = new StringBuilder();
		sbWhere.append(" where ");
		for (Annotation annoClass : obj.getClass().getAnnotations()) {
			tabelas = (Entity) annoClass;
			if (annoClass instanceof Entity) {
				sb.append("  update " + tabelas.tableName());
			}

		}
		sb.append(" set ");
		for (Field field : obj.getClass().getDeclaredFields()) {
			int totalCampos = obj.getClass().getDeclaredFields().length;
			linhaAtual += 1;
			for (Annotation anno : field.getAnnotations()) {
				if (anno instanceof Fields) {
					configuraCampo = (Fields) anno;
					String aspas = (configuraCampo.isEspecialChar())? "'" : "";
					String virgula = (linhaAtual < totalCampos) ? ", " : " ";
					sb.append("  " + configuraCampo.fieldName() + " ="+aspas+":"+field.getName().toUpperCase()+aspas+virgula);
	                if (configuraCampo.isKey()){
	                	keys.put(configuraCampo.fieldName(), field.getName().toUpperCase());
	                }
				}
			}
		}
		
	    if (!keys.isEmpty()) {
            for (String name : keys.keySet()) {
               int totalCamposWhere=keys.size();
               linhaAtualWhere +=1;
               String aspas = (configuraCampo.isEspecialChar())? "'" : "";
   			   String operador = (linhaAtualWhere < totalCamposWhere) ? " and " : " ";
               sbWhere.append("  " + name + " ="+aspas+":"+keys.get(name)+aspas+operador);
            }
         }
        sb.append(sbWhere.toString());
		TemplateEngine te = new TemplateEngine();
		return te.getSQLQueryAutomatic(sb.toString(),obj);

	}

}
